<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false" style="min-width: 1200px;"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"
             label-width="120px"
             label-position="left">
      <el-form-item label="客户端分类" prop="userAgent">
        <el-radio-group v-model="dataForm.userAgent" size="small" @change="userAgentChange">
          <el-radio label="android" border>android</el-radio>
          <el-radio label="ios" border>ios</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="app分类" prop="contentType">
        <el-select v-model="dataForm.appCode">
          <el-option
            v-if="appCodeOptions"
            v-for="item in appCodeOptions"
            :key="item.code"
            :label="item.label"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="app的包名" prop="appPkgName" v-if="dataForm.userAgent==='android'">
        <el-input v-model="dataForm.appPkgName" placeholder="app的包名"></el-input>
      </el-form-item>
      <el-form-item label="md5" prop="md5" v-if="dataForm.userAgent==='android'">
        <el-input v-model="dataForm.md5" placeholder="md5"></el-input>
      </el-form-item>
      <el-form-item label="更新标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="更新标题"></el-input>
      </el-form-item>
      <el-form-item label="app名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="app名称"></el-input>
      </el-form-item>
      <el-form-item label="app版本号" prop="version">
        <el-input v-model.number="dataForm.version" type="number" placeholder="app版本号(数字 例如:100)"></el-input>
      </el-form-item>
      <el-form-item label="apk的url" prop="apkUrl" style="width: 100%" v-if="dataForm.userAgent==='android'">
        <div style="display: flex;margin-bottom: 10px;">
          <el-tooltip effect="dark" :content="dataForm.apkUrl?dataForm.apkUrl:'请先上传apk'" placement="top-start">
            <el-input v-model="dataForm.apkUrl" placeholder="apk的url" disabled></el-input>
          </el-tooltip>
          <el-upload
            action=""
            :show-file-list="false"
            accept=".apk"
            :http-request="fnUploadRequest"
            :on-error="handleUploadError"
            :before-upload="beforeUploadApk"
            :on-success="handleApkSuccess">
            <el-button type="primary" style="margin-left: 10px;">上传apk</el-button>
          </el-upload>
        </div>
        <el-progress :percentage="progress" v-if="progress>0"></el-progress>
      </el-form-item>
      <el-form-item label="更新说明" prop="upgradeInfo">
        <el-input v-model="dataForm.upgradeInfo" type="textarea" placeholder="200字内" :rows="5"
                  maxlength="200"></el-input>
      </el-form-item>
      <el-form-item label="强制更新" prop="force">
        <el-radio-group v-model="dataForm.force" size="small">
          <el-radio :label="0" border>否</el-radio>
          <el-radio :label="1" border>是</el-radio>
        </el-radio-group>
      </el-form-item>
      <input type="text" style="display: none;">
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import oss from '../../../utils/aliOss'

  export default {
    data () {
      var validateAppPkgName = (rule, value, callback) => {
        if (this.dataForm.userAgent === 'android') {
          if (value) {
            callback()
          } else {
            callback(new Error('app的包名不能为空'))
          }
        } else {
          callback()
        }
      }
      var validateMd5 = (rule, value, callback) => {
        if (this.dataForm.userAgent === 'android') {
          if (value) {
            callback()
          } else {
            callback(new Error('app的md5不能为空'))
          }
        } else {
          callback()
        }
      }
      var validateUrl = (rule, value, callback) => {
        if (this.dataForm.userAgent === 'android') {
          if (value) {
            callback()
          } else {
            callback(new Error('app的url不能为空'))
          }
        } else {
          callback()
        }
      }
      return {
        visible: false,
        progress: 0,
        appCodeOptions: [
          {code: 'picbook', label: '制药阅读'},
          {code: 'english', label: '制药英语'}
        ],
        dataForm: {
          id: '',
          userAgent: 'android',
          appPkgName: '',
          appCode: 'picbook',
          title: '',
          name: '',
          version: '',
          appVersionName: '',
          apkUrl: '',
          upgradeInfo: '',
          md5: '',
          force: 0
        },
        dataRule: {
          appCode: [
            {required: true, message: 'app的分类未选择', trigger: 'blur'}
          ],
          appPkgName: [
            {validator: validateAppPkgName, trigger: 'blur'}
          ],
          title: [
            {required: true, message: '更新标题不能为空', trigger: 'blur'}
          ],
          name: [
            {required: true, message: 'app名称不能为空', trigger: 'blur'}
          ],
          version: [
            {required: true, message: 'app版本号不能为空', trigger: 'blur'}
          ],
          apkUrl: [
            {validator: validateUrl, trigger: 'blur'}
          ],
          appVersionName: [
            {required: true, message: 'app版本名不能为空', trigger: 'blur'}
          ],
          upgradeInfo: [
            {required: true, message: '更新说明不能为空', trigger: 'blur'}
          ],
          md5: [
            {validator: validateMd5, trigger: 'blur'}
          ],
          force: [
            {required: true, message: '是否强制更新(1是,0否)不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.progress = 0
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/picbook/appupgrade/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm = data.data.appUpgrade
              }
            })
          }
        })
      },
      userAgentChange () {
        this.$refs['dataForm'].clearValidate()
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.userAgent === 'ios') {
              this.dataForm.appPkgName = ''
              this.dataForm.md5 = ''
              this.dataForm.apkUrl = ''
            }
            this.$http({
              url: this.$http.adornUrl(`/picbook/appupgrade/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                appUpgrade: this.dataForm
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  // duration: 1500,
                  duration: 500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      uploadProgress (p) {
        this.progress = Math.floor(p * 100)
      },
      /**
       * @description [fnUploadRequest 覆盖默认的上传行为，实现自定义上传]
       * @param    {object}   option [上传选项]
       * @return   {null}   [没有返回]
       */
      async fnUploadRequest (option) {
        oss.ossUploadFile(option, this.uploadProgress)
      },
      // apk上传之前
      beforeUploadApk (file) {
        // if (file.type.indexOf('application/vnd.android.package-archive') < 0) {
        //   this.$message.error('apk格式不正确')
        //   return false
        // }
        let name = file.name
        //字符串截取为了兼容火狐，火狐浏览器获取apk文件的type为空
        var apk = name.substring(name.length - 3, name.length)
        const isAPK = apk === 'apk'
        if (!isAPK) {
          this.$message.error('上传只能是 apk 格式安装包!')
        }
        return isAPK
      },
      // //apk上传成功后
      // handleApkSuccess (response, file, fileList) {
      //   this.dataForm.apkUrl = file.url
      //   this.$message.success('上传成功')
      // },
      // 添加多个文件事件
      beyondFile (files, fileList) {
        this.$message({
          message: '一次只能上传一个apk文件，请删除重新上传',
          type: 'success'
        })
      },
      // 上传apk文件
      handleApkSuccess (response, file, fileList) {
        if (response == null) {
          return
        }
        let retUrl = response.res.requestUrls[0].split('?')[0]
        if (retUrl) {
          if (window.SITE_CONFIG['baseUrl'] == 'https://xxx-app-api.xxx.cn') {
            this.dataForm.apkUrl = retUrl.replace('https://xxx-edu-epxxx.oss-cn-hangzhou.aliyuncs.com', 'https://huiben-oss-cdn.xxx.cn')
          } else {
            this.dataForm.apkUrl = retUrl
          }
          this.$message.success('上传成功')
        }
      },
      //上传失败
      handleUploadError (err, file, fileList) {
        this.$message.error('上传失败')
      },
    }
  }
</script>
<style lang="less">
  /** 去除input输入框样式 */
  input[type=number]::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
</style>
